home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 14537 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: news.cern.ch!danpop
  2. From: danpop@mail.cern.ch (Dan Pop)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: char* still alive after free ???
  5. Date: 15 Apr 96 17:33:20 GMT
  6. Organization: CERN European Lab for Particle Physics
  7. Message-ID: <danpop.829589600@news.cern.ch>
  8. References: <317269EA.11BB93C2@studbox.uni-stuttgart.de>
  9. NNTP-Posting-Host: ues5.cern.ch
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=US-ASCII
  12. Content-Transfer-Encoding: 7bit
  13. X-Newsreader: NN version 6.5.0 #7 (NOV)
  14.  
  15. In <317269EA.11BB93C2@studbox.uni-stuttgart.de> Markus Heller <Markus.Heller@studbox.uni-stuttgart.de> writes:
  16.  
  17. >I have a global variable :
  18. >
  19. >char *text=NULL;
  20. >
  21. >I want to use it to store different "strings" (at diffreent times).
  22. >E.g., if I want to sore 10 characters in text, I do a 
  23. >text=(char *) malloc(10*sizeof(char));
  24.  
  25. 1. 10*sizeof(char) is overkill, plain 10 would do as well.
  26.  
  27. 2. If you want to store 10 charaters as a C string, allocate space for
  28.    11 characters.  C strings are null-terminated.
  29.  
  30. 3. The cast is a bad idea.  Don't use it.
  31.  
  32. >When I want to use text to store 3 other characters, I first do a
  33. >free(text); text=NULL; and finally a
  34. >text=(char *) malloc(3*sizeof(char));
  35. >But to my surprise there are still the 4thh to 10th charcter of
  36. >text contained before the free(text)/malloc... ???
  37.  
  38. Why not?  The point is that, after text = malloc(3), it is _illegal_
  39. to attempt to access the 4th to 10th characters.  Your program could
  40. simply crash and burn with a segmentation fault.  text is now pointing
  41. to the first character of an array of 3 characters, period.
  42.  
  43. >This happens under linux, but why ?
  44.  
  45. For the simple reason that malloc is returning the same address as in
  46. the previous call and the old characters have retained their values.
  47. Calling free() isn't likely to alter the contents of the memory block
  48. being returned to the memory allocator.
  49.  
  50. Dan
  51. --
  52. Dan Pop
  53. CERN, CN Division
  54. Email: danpop@mail.cern.ch 
  55. Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  56.